<template>
  <div>
    <div class="buttons">
      <el-button size="mini" type="primary" icon="el-icon-plus" @click="addField">新增</el-button>
      <el-button size="mini" type="danger" :disabled="btnDis" icon="el-icon-minus" @click="delField">删除</el-button>
      <!--      <el-button-->
      <!--        icon="el-icon-news"-->
      <!--        size="mini"-->
      <!--        type="success"-->

      <!--        @click="flowField"-->
      <!--      >流程</el-button>-->
    </div>
    <el-table
      ref="multipleTable"
      :data="dbPropertyList"
      tooltip-effect="dark"
      style="width: 100%"
      row-key="id"
      @selection-change="selectionChangeHandle"
      @cell-mouse-enter.once="rowDrop"
    >
      <el-table-column type="selection" align="center" width="55" :selectable="checkSelectable" />
      <el-table-column :label="$t('#')" prop="index" align="center" width="50">
        <template slot="header">
          <el-tooltip class="item" effect="light" content="可拖拽排序" placement="top-start">
            <i class="el-icon-s-promotion" />
          </el-tooltip>
        </template>
        <template>
          <span style="cursor:move;" class="handle">
            <i class="el-icon-sort" />
          </span>
        </template>

      </el-table-column>
      <el-table-column prop="dbFieldTxt" label="字段备注" width="240px">
        <template slot="header" slot-scope="{}">
          <i style="color: #ff4949; margin-right: 4px">*</i>
          <span>字段备注</span>
        </template>
        <template slot-scope="scope">
          <el-form-item>
            <el-input
              v-model="scope.row.dbFieldTxt"
              :disabled=" isDisabled(scope.row)"
              show-word-limit
              :maxlength="30"
              @change="convert(scope.row)"
            /> </el-form-item></template>
      </el-table-column>
      <el-table-column prop="dbFieldName" label="字段名称" width="240px">
        <template slot="header" slot-scope="{}">
          <i style="color: #ff4949; margin-right: 4px">*</i>
          <span>字段名称</span>
        </template>
        <template slot-scope="scope">
          <el-form-item>
            <el-input
              v-model="scope.row.dbFieldName"
              :disabled=" isDisabled(scope.row)"
              show-word-limit
              :maxlength="50"
            /> </el-form-item></template>
      </el-table-column>
      <el-table-column prop="dbLength" label="字段长度" width="80px">
        <template slot-scope="scope">
          <el-form-item>
            <el-input
              v-model="scope.row.dbLength"
              :disabled=" isDisabled(scope.row)"
            /> </el-form-item></template>
      </el-table-column>
      <el-table-column prop="dbPointLength" label="小数点" width="80px">
        <template slot-scope="scope">
          <el-form-item>
            <el-input
              v-model="scope.row.dbPointLength"
              :disabled=" isDisabled(scope.row)"
            /> </el-form-item></template>
      </el-table-column>
      <el-table-column prop="dbDefaultVal" label="字段类型" width="240px">
        <template slot-scope="scope">
          <el-form-item>
            <el-select
              v-model="scope.row.dbType"
              placeholder="请选择"
              :disabled=" isDisabled(scope.row)"
              @change="dbPointLengthLimit(scope.$index, scope.row)"
            >
              <el-option v-for="item in options" :key="item.value" :label="item.title" :value="item.value" />
            </el-select> </el-form-item></template>
      </el-table-column>
      <el-table-column prop="dbDefaultVal" label="字段默认值" width="240px">
        <template slot-scope="scope">
          <el-form-item>
            <el-input
              v-model="scope.row.dbDefaultVal"
              :disabled=" isDisabled(scope.row)"
            /> </el-form-item></template>
      </el-table-column>

      <el-table-column label="允许空值">
        <template slot-scope="scope">
          <el-checkbox
            v-model="scope.row.dbIsNull"
            :checked="scope.row.dbIsNull"
            :disabled=" isDisabled(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import Sortable from 'sortablejs'
import { delDbFieldIds, updateHeadSyncStatus } from '@/api/system/desform/onlineForm/onlCgformHead'
import { convertPinying } from '@/api/system/desform/onlineForm/onlCgformHead'
import MD5 from '@/api/md5'
import axios from 'axios'
const MySQLKeywords = ['ADD', 'ALL', 'ALTER', 'ANALYZE', 'AND', 'AS', 'ASC', 'ASENSITIVE',
  'BEFORE', 'BETWEEN', 'BIGINT', 'BINARY', 'BLOB', 'BOTH', 'BY', 'CALL', 'CASCADE', 'CASE',
  'CHANGE', 'CHAR', 'CHARACTER', 'CHECK', 'COLLATE', 'COLUMN', 'CONDITION', 'CONNECTION',
  'CONSTRAINT', 'CONTINUE', 'CONVERT', 'CREATE', 'CROSS', 'CURRENT_DATE', 'CURRENT_TIME',
  'CURRENT_TIMESTAMP', 'CURRENT_USER', 'CURSOR', 'DATABASE', 'DATABASES', 'DAY_HOUR',
  'DAY_MICROSECOND', 'DAY_MINUTE', 'DAY_SECOND', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT',
  'DELAYED', 'DELETE', 'DESC', 'DESCRIBE', 'DETERMINISTIC', 'DISTINCT', 'DISTINCTROW',
  'DIV', 'DOUBLE', 'DROP', 'DUAL', 'EACH', 'ELSE', 'ELSEIF', 'ENCLOSED', 'ESCAPED',
  'EXISTS', 'EXIT', 'EXPLAIN', 'FALSE', 'FETCH', 'FLOAT', 'FLOAT4', 'FLOAT8', 'FOR',
  'FORCE', 'FOREIGN', 'FROM', 'FULLTEXT', 'GOTO', 'GRANT', 'GROUP', 'HAVING', 'HIGH_PRIORITY',
  'HOUR_MICROSECOND', 'HOUR_MINUTE', 'HOUR_SECOND', 'IF', 'IGNORE', 'IN', 'INDEX', 'INFILE',
  'INNER', 'INOUT', 'INSENSITIVE', 'INSERT', 'INT', 'INT1', 'INT2', 'INT3', 'INT4', 'INT8',
  'INTEGER', 'INTERVAL', 'INTO', 'IS', 'ITERATE', 'JOIN', 'KEY', 'KEYS', 'KILL', 'LABEL',
  'LEADING', 'LEAVE', 'LEFT', 'LIKE', 'LIMIT', 'LINEAR', 'LINES', 'LOAD', 'LOCALTIME',
  'LOCALTIMESTAMP', 'LOCK', 'LONG', 'LONGBLOB', 'LONGTEXT', 'LOOP', 'LOW_PRIORITY',
  'MATCH', 'MEDIUMBLOB', 'MEDIUMINT', 'MEDIUMTEXT', 'MIDDLEINT', 'MINUTE_MICROSECOND',
  'MINUTE_SECOND', 'MOD', 'MODIFIES', 'NATURAL', 'NOT', 'NO_WRITE_TO_BINLOG', 'NULL',
  'NUMERIC', 'ON', 'OPTIMIZE', 'OPTION', 'OPTIONALLY', 'OR', 'ORDER', 'OUT', 'OUTER',
  'OUTFILE', 'PRECISION', 'PRIMARY', 'PROCEDURE', 'PURGE', 'RAID0', 'RANGE', 'READ',
  'READS', 'REAL', 'REFERENCES', 'REGEXP', 'RELEASE', 'RENAME', 'REPEAT', 'REPLACE',
  'REQUIRE', 'RESTRICT', 'RETURN', 'REVOKE', 'RIGHT', 'RLIKE', 'SCHEMA', 'SCHEMAS',
  'SECOND_MICROSECOND', 'SELECT', 'SENSITIVE', 'SEPARATOR', 'SET', 'SHOW', 'SMALLINT',
  'SPATIAL', 'SPECIFIC', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'SQL_BIG_RESULT',
  'SQL_CALC_FOUND_ROWS', 'SQL_SMALL_RESULT', 'SSL', 'STARTING', 'STRAIGHT_JOIN', 'TABLE',
  'TERMINATED', 'THEN', 'TINYBLOB', 'TINYINT', 'TINYTEXT', 'TO', 'TRAILING', 'TRIGGER',
  'TRUE', 'UNDO', 'UNION', 'UNIQUE', 'UNLOCK', 'UNSIGNED', 'UPDATE', 'USAGE', 'USE',
  'USING', 'UTC_DATE', 'UTC_TIME', 'UTC_TIMESTAMP', 'VALUES', 'VARBINARY', 'VARCHAR',
  'VARCHARACTER', 'VARYING', 'WHEN', 'WHERE', 'WHILE', 'WITH', 'WRITE', 'X509', 'XOR',
  'YEAR_MONTH', 'ZEROFILL']
export default {
  name: 'DbProperty',
  props: {
    data: {
      type: Array,
      required: true
    },
    // 备注翻译字段名方式  拼音/英文
    translation: {
      type: String,
      default: () => undefined
    }
  },
  data() {
    var only = (rule, value, callback) => {
      if (!value) {
        this.$message.error('字段名不能为空')
        return callback(new Error())
      } else {
        const isKey = MySQLKeywords.includes(value)
        if (isKey) {
          this.$message.error('字段名不能为关键字')
          return callback(new Error())
        }
        callback()
      }
    }

    return {
      i: 1,
      btnDis: true,
      multipleTable: [],
      tableData: [],
      MySQLKeywords: MySQLKeywords,
      options: [
        { title: '字符串(String)', value: 'string' },
        { title: '整数(Int)', value: 'int' },
        { title: '小数(Double)', value: 'double' },
        { title: '日期(Date)', value: 'Date' },
        { title: '金额(BigDecimal)', value: 'BigDecimal' },
        { title: '文本(Text)', value: 'Text' }
        // { title: 'Blob', value: 'Blob' }
      ],
      dbFieldName: [
        { validator: only, trigger: 'blur' }
      ]

    }
  },
  computed: {
    ...mapState('dbAbout', ['dbPropertyList']),
    guid() {
       return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random() * 16 | 0
              var v = c === 'x' ? r : (r & 0x3 | 0x8)
          return v.toString(16)
      })
    }
  },
  watch: {
    dbPropertyList: {
      handler() {
        this.wrapperData()
        this.$nextTick(() => {
          // 滚动表格到底部
          this.$refs.multipleTable.bodyWrapper.scrollTop = this.$refs.multipleTable.bodyWrapper.scrollHeight
        })
      },
      deep: true
    }
  },
  created() {
    this.wrapperData()
    //  this.rowDrop()
  },
  methods: {
    ...mapActions('dbAbout', ['initDbProperty', 'addDbProperty', 'delDbProperty', 'resetIndex']),
    // 封装成这个表单需要的数据
    wrapperData() {
      this.tableData = []
      this.dbPropertyList.forEach(e => {
        const obj = {
          'id': e.id,
          'index': e.index,
          'dbFieldName': e.dbFieldName,
          'dbFieldTxt': e.dbFieldTxt,
          'dbDefaultVal': e.dbDefaultVal,
          'dbLength': e.dbLength,
          'dbIsNull': e.dbIsNull ? 1 : 0,
          'dbType': e.dbType,
          'dbPointLength': e.dbPointLength
        }
        this.tableData.push(obj)
      })
    },
    addField() {
      const row = {
        dbFieldName: '',
        dbLength: '100',
        dbPointLength: '0',
        dbDefaultVal: '',
        dbFieldTxt: '',
        dbIsNull: true,
        dbType: 'string',
        index: 0
      }
      this.addDbProperty(row)
    },
    // 禁止选中的条件
    checkSelectable(row) {
      return !this.isDisabled(row)
    },
    // 删除字段
    delField() {
      this.delDbProperty(this.multipleTable)
      const ids = []
      this.multipleTable.map(item => {
        if (item.id !== undefined && item.id !== '' && item.id !== null && !item.id.includes('add')) {
          ids.push(item.id)
        }
      })
      this.$refs.multipleTable.clearSelection()
      // 这里应该更改同步的字段状态
      if (ids.length > 0) {
        delDbFieldIds(ids.toString())
        updateHeadSyncStatus(ids[0])
      }
    },
    // 添加流程字段
    flowField() {
      const actStatus = {
        dbFieldName: 'act_status',
        dbLength: '2',
        dbPointLength: '0',
        dbDefaultVal: '',
        dbFieldTxt: '流程状态',
        dbIsNull: true,
        dbType: 'string',
        index: 0
      }
      const actId = {
        dbFieldName: 'act_id',
        dbLength: '64',
        dbPointLength: '0',
        dbDefaultVal: '',
        dbFieldTxt: '流程Id',
        dbIsNull: true,
        dbType: 'string',
        index: 0
      }
      const actTitle = {
        dbFieldName: 'act_title',
        dbLength: '100',
        dbPointLength: '0',
        dbDefaultVal: '',
        dbFieldTxt: '流程标题',
        dbIsNull: true,
        dbType: 'string',
        index: 0
      }
      const act_s = this.dbPropertyList.find(item => item.dbFieldName === 'act_status')
      const act_t = this.dbPropertyList.find(item => item.dbFieldName === 'act_title')
      const act_i = this.dbPropertyList.find(item => item.dbFieldName === 'act_id')
      if (!act_s) {
        this.addDbProperty(actStatus)
      }
      if (!act_t) {
        this.addDbProperty(actTitle)
      }
      if (!act_i) {
        this.addDbProperty(actId)
      }
    },
    selectionChangeHandle(val) {
      this.multipleTable = val
      this.btnDis = !(val.length > 0)
    },
    // 行拖拽
    rowDrop() {
      const tbody = this.$refs.multipleTable.$el.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        handle: '.handle',
        animation: 500,
        fallbackOnBody: true,
        onAdd: function() { // 拖拽时候添加有新的节点的时候发生该事件
        },
        onUpdate: function() { // 拖拽更新节点位置发生该事件
          // console.log('onUpdate.foo:', [evt.item, evt.from])
        },
        onRemove: function() { // 删除拖拽节点的时候促发该事件
          // console.log('onRemove.foo:', [evt.item, evt.from])
        },
        onStart: function() { // 开始拖拽出发该函数
          // console.log('onStart.foo:', [evt.item, evt.from])
        },
        onSort: function() { // 发生排序发生该事件
          // console.log('onUpdate.foo:', [evt.item, evt.from])
        },
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
          _this.resetIndex({ newIndex, oldIndex })
        }
      })
    },
    getRowKeys(row) {
      return row.index === null || row.id === undefined ? new Date().getTime() : row.index
    },
    convert(row) {
      if (this.translation === 'en_us') {
        this.convertEnglish(row)
      } else {
       this.convertPinying(row)
      }
    },
    convertPinying(row) {
      if (row.dbFieldTxt) {
        row.dbFieldTxt = row.dbFieldTxt.replaceAll('^', '')
        convertPinying(row.dbFieldTxt).then(res => {
          if (res.data) {
            row.dbFieldName = res.data.replaceAll(' ', '')
          }
        })
      }
    },
    convertEnglish(row) {
      // 请求百度翻译参数
     const translationParams = {
          q: row.dbFieldTxt,
          from: 'zh',
          to: 'en',
          appid: '20201127000627254',
          salt: '12345',
          key: 'uEaHcpntHBYsTjPTAe7u',
          domain: 'finance',
          sign: ''
      }
      if (row.dbFieldTxt) {
        translationParams.sign = MD5(translationParams.appid + translationParams.q + translationParams.salt + translationParams.domain + translationParams.key)
        axios({
          method: 'get',
          url: '/api/trans/vip/fieldtranslate?' +
            'q=' + translationParams.q +
            '&from=' + translationParams.from +
            '&to=' + translationParams.to +
            '&appid=' + translationParams.appid +
            '&salt=' + translationParams.salt +
            '&domain=' + translationParams.domain +
            '&sign=' + translationParams.sign
        }).then(res => {
          console.log(res, 'resresres')
          var dbFieldName = res.data.trans_result[0].dst.replace(/( |^)[a-z]/g, (L) => L.toUpperCase())
          console.log(dbFieldName, 'dbFieldName')
          dbFieldName = dbFieldName.toLowerCase().replace(/\s/g, '_')

          // dbFieldName = dbFieldName.replaceAll(' ', '')
          row.dbFieldName = dbFieldName
        })
      }
    },
    // 字段类型，除String外小数点归0
    dbPointLengthLimit(index, row) {
      if (row) {
        if (row !== 'string') {
          this.dbPropertyList[index].dbPointLength = 0
        }
      }
    },
    isDisabled(row) {
        if (row.dbFieldName === 'id' ||
        row.dbFieldName === 'create_by' ||
        row.dbFieldName === 'create_time' ||
        row.dbFieldName === 'update_by' ||
        row.dbFieldName === 'update_time') {
          return true
        }
        return false
    }
  }

}
</script>

<style scoped>
.buttons {
  margin-bottom: 10px;
}

/* 修改行的最小高度 */
.dataForm .el-row .el-form-item {
  min-height: 0px;
}
</style>
